package com.zhongc.advance.web.initbinder;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
/**
 * 
 * 
 *                       
 * @Filename InternalWebBindingInitializer.java
 *
 * @Description 
 *
 * @Version 1.0
 *
 * @Author zhongc
 *
 * @Email zhong_ch@foxmail.com
 *       
 * @History 
 *<li>Author: zhongc</li>
 *<li>Date: 2015年7月13日</li>
 *<li>Version: 1.0</li>
 *<li>Content: create</li>
 *
 */
public class InternalWebBindingInitializer implements WebBindingInitializer{
	
	private static final SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
	
	private static final SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public void initBinder(WebDataBinder binder, WebRequest request) {
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
			@Override
			public void setAsText(String text) throws IllegalArgumentException {
				Date date = null;
				if(text != null && text.length() > 0){
					try {
						if(text.length() > 10){
							date = format2.parse(text);
						}else{
							date = format1.parse(text);
						}
					} catch (ParseException e) {
						e.printStackTrace();
						throw new IllegalArgumentException("不合法的日期格式:" + text);
					}
				}
				setValue(date);
			}
		});
		
	}
	
}
